<?php
class Response{

 /**
 * 综合方式输出通讯数据(json/xml)
 * @ param integer $code 状态码
 * @ param string $message 提示信息
 * @ param array $data 数据
 * @ param string $type 数据类型(json/xml)
 * ruturn string
 */
    public static function show($code,$massage = '',$data = array(),$type='json'){
            if(!is_numeric($code)){
                return '';
            }
            $result = array(
                    'code' => $code,
                    'massage' => $massage,
                    'data' => $data,
             );
             if ($type == 'json'){
                self::json($code,$massage,$data);
                exit;
             } elseif ($type == 'array') {
                 var_dump($result);
             }elseif ($type == 'xml') {
                 self::xmlEncode($code,$massage,$data);
                 exit;
             }    else{
                //TODO
             }
    }

 /**
 * 按json方式输出通讯数据
 * @ param integer $code 状态码
 * @ param string $message 提示信息
 * @ param array $data 数据
 * ruturn string
 */
        public static function json($code,$massage = '',$data = array()){

            if(!is_numeric($code)){
                return '';
            }
            $result = array(
                    'code' => $code,
                    'massage' => $massage,
                    'data' => $data
                );
            echo json_encode($result);
            exit;
        }


 /**
 * 按xml方式输出通讯数据
 * @ param integer $code 状态码
 * @ param string $message 提示信息
 * @ param array $data 数据
 * ruturn string
 */
        public static function xmlEncode($code,$massage = '',$data = array()){
           if(!is_numeric($code)){
                return '';
            }
            $result = array(
                    'code' => $code,
                    'massage' => $massage,
                    'data' => $data
             );

            header("Content-Type:text/xml");
            $xml = "<?xml version ='1.0' encoding='UTF-8'?>\n";
            $xml .= "<root>\n";
            $xml .= self::xmlToEncode($result);
            // $xml .= "<code>200</code>\n";
            // $xml .= "<massage>返回成功</massage>\n";
            // $xml .= "<data>\n";
            // $xml .= "<id>1</id>\n";
            // $xml .= "<name>liuliang</name>\n";
            // $xml .= "<age>18</age>\n";
            // $xml .= "</data>\n";
            $xml .= "</root>\n";
            echo $xml;
        }
        public static function xmlToEncode($data){
            $xml = $attr = "";
            foreach($data as $key => $value){
                if(is_numeric($key)){
                    $attr = "id = '{$key}'";
                    $key = "item";
                }
                $xml .= "<{$key} {$attr}>";
                $xml .= is_array($value) ? self::xmlToEncode($value) : $value;
                $xml .= "</{$key}>\n";
            }
            return $xml;
        }
}
